# 自定义文件存储类

from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client
from django.conf import settings


class FDFSStorage(Storage):
    """FDFS文件存储类"""

    def _save(self, name, content):

        # 将文件上传到ＦＤＳ系统
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)

        res = client.upload_by_buffer(content.read())

        # 判断是否上传成功
        if res.get('Status') != 'Upload successed.':
            raise Exception('上传文件到FDS系统失败')

        # 获取文件id
        file_id = res.get('Remote file_id')

        return file_id

    def exists(self, name):
        return False

    def url(self, name):
        return settings.FDFS_URL + name
